﻿Imports System.Globalization, System.Security.Permissions, System.Windows.Forms, EnvDTE


''' <summary>
''' Summary description for MyControl.
''' </summary>
Public Class ToolWindowControl
    Inherits UserControl
    Public Property IsDebuggerConnected As Boolean
    Private Property IsNotCottectedMessageShown As Boolean


#Region "       Overrides       >>>"


    ''' <summary>
    ''' Enable the IME status handling for this control.
    ''' </summary>
    Protected Overrides ReadOnly Property CanEnableIme() As Boolean
        Get
            Return True
        End Get
    End Property


    ''' <summary>
    ''' Let this control process the mnemonics.
    ''' </summary>
    <UIPermission(SecurityAction.LinkDemand, Window:=UIPermissionWindow.AllWindows)>
    Protected Overrides Function ProcessDialogChar(ByVal charCode As Char) As Boolean
        ' If we're the top-level form or control, we need to do the mnemonic handling
        If charCode <> " "c AndAlso ProcessMnemonic(charCode) Then
            Return True
        End If
        Return MyBase.ProcessDialogChar(charCode)
    End Function


    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    ''' <stepthrough></stepthrough>
    Protected Overrides Sub OnLoad(ByVal e As EventArgs)
        MyBase.OnLoad(e)
        If Not DesignMode AndAlso Mod_Utilities.DTE.Debugger.CurrentMode = dbgDebugMode.dbgBreakMode Then
            RunIntruding()
        End If
    End Sub


#End Region


#Region "       Controls        >>>"

    Private Sub intellisenseTextBox1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles intellisenseTextBox1.Load
    End Sub
    ''' <summary>Check To see if this is the Right Control for the Event</summary> 
    Private Sub connectToolStripButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles connectToolStripButton.Click
        Me.Cursor = Cursors.WaitCursor
        Try
            'Mod_Utilities.Connect() '<-- Date: 10/25/2011   Aaron: This Fixes A Problem, But I think I can make A Real Fix Soon!!!
            'If Not Mod_Utilities.IsConnected = True OrElse Not Mod_Utilities.ToolWindowControl_Only Is Nothing Then Mod_Utilities.IsConnected = True
            'UpdateContextTypeIfChanged()

            If Mod_Utilities.DTE.Debugger.CurrentMode = dbgDebugMode.dbgBreakMode Then
                Dim currentFunction As String = Mod_Utilities.DTE.Debugger.CurrentStackFrame.FunctionName

                Mod_Utilities.Log("ExtendedImmediateAddInn - Connect")
                Mod_Utilities.Log("Current Func: " & currentFunction)

                Dim Work =
                    Function(x As Object, args As ResolveEventArgs) As Reflection.Assembly
                        If args.Name = GetCurrentType.Assembly.FullName Then
                            Return GetCurrentType.Assembly
                        Else
                            Return Nothing
                        End If
                    End Function


                Mod_Utilities.Log("-> not cached already, have to analyze " & currentFunction)
                'Mod_Utilities.Log("CurrentType: " & GetCurrentType.ToString())     '<-- This was Causing an Error

                Dim context = Mod_Utilities.GetContextType()
                Mod_Utilities.Log("ContextType (compiled in background): " & context.ToString())

                AddHandler AppDomain.CurrentDomain.AssemblyResolve, Work
                Mod_Utilities.ToolWindowControl_Only.SetContextType(context)
                RemoveHandler AppDomain.CurrentDomain.AssemblyResolve, Work

                Mod_Utilities.LastStackFunction = currentFunction
                Mod_Utilities.Log("Done.")
            End If

            IsDebuggerConnected = True
        Catch exc As Exception
            MessageBox.Show("Konnte nicht verbinden: " & exc.Message & " " & exc.StackTrace)
        End Try
        Me.Cursor = Cursors.Arrow
    End Sub


    Private Sub intellisenseTextBox1_SourceCodeChanged(ByVal sender As Object, ByVal e As EventArgs) Handles intellisenseTextBox1.SourceCodeChanged
        If Not IsDebuggerConnected AndAlso Not IsNotCottectedMessageShown Then
            Dim msg As String = "You are not yet connected to a debugger, intellisense environment may be wrong. Please connect before to a running debugger before executing the intruding method."
            toolTip1.Show(msg, intellisenseTextBox1, 20000)
            IsNotCottectedMessageShown = True
        End If

        Mod_Utilities.SourceCode = intellisenseTextBox1.Text
    End Sub



    ''' <summary>Check To see if this is the Right Control for the Event</summary> 
    Private Sub pictureBox1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles pictureBox1.Click
        MsgBox("Splash Screen not Imported Yet")
    End Sub



    ''' <summary>
    ''' Upgrade this so After the MessageBox Shows Then the Form will not Load
    ''' </summary>
    ''' <remarks></remarks>
    ''' <stepthrough>Enabled</stepthrough>
    <DebuggerStepThrough()>
    Private Sub RunIntruding()
        If Mod_Utilities.DTE.Debugger.CurrentMode = dbgDebugMode.dbgBreakMode Then
            Dim injector As New Injector(GetResolver.ReferencedAssemblies, Mod_Utilities.LocalReachableMembers.ToList())
            injector.Execute()
        End If
    End Sub



    ''' <summary>Check To see if this is the Right Control for the Event</summary> 
    Private Sub btRun_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btRun.Click
        Mod_Utilities.SourceCode = intellisenseTextBox1.Text
        RunIntruding()
    End Sub


#End Region




    <DebuggerStepThrough()>
    Public Sub New()
        InitializeComponent()
        If DesignMode = False Then
            Mod_Utilities.ToolWindowControl_Only = Me
            'Why Show the Control Then Hide it?
            'Me.Visible = False : DoubleBuffered = True : Me.Visible = True
            DoubleBuffered = True
        End If
    End Sub


    ''' <summary>
    '''
    ''' </summary>
    ''' <param name="contextType"></param>
    Public Sub SetContextType(ByVal contextType As Type)
        intellisenseTextBox1.ContextType = contextType
        IsDebuggerConnected = True
        btRun.Enabled = True
        btRun.Text = "Run Intruding Method"
    End Sub


    ' ''' <summary>
    ' ''' Get this to Work 100% of the Time. Currently It will not Connect If it has already Connected before
    ' ''' </summary>
    ' ''' <remarks></remarks>
    ' ''' <stepthrough></stepthrough>
    'Private Sub UpdateContextTypeIfChanged()
    '    If Mod_Utilities.IsConnected AndAlso Mod_Utilities.DTE.Debugger.CurrentMode = dbgDebugMode.dbgBreakMode Then
    '        Dim currentFunction As String = Mod_Utilities.DTE.Debugger.CurrentStackFrame.FunctionName

    '        Mod_Utilities.Log("ExtendedImmediateAddInn - Connect")
    '        Mod_Utilities.Log("Current Func: " & currentFunction)

    '        If currentFunction <> Mod_Utilities.LastStackFunction Then
    '            Dim Work =
    '                Function(sender As Object, args As ResolveEventArgs) As Reflection.Assembly
    '                    If args.Name = GetCurrentType.Assembly.FullName Then
    '                        Return GetCurrentType.Assembly
    '                    Else
    '                        Return Nothing
    '                    End If
    '                End Function


    '            Mod_Utilities.Log("-> not cached already, have to analyze " & currentFunction)
    '            Mod_Utilities.Log("CurrentType: " & GetCurrentType.ToString())

    '            Dim context = Mod_Utilities.GetContextType()
    '            Mod_Utilities.Log("ContextType (compiled in background): " & context.ToString())

    '            'AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf Mod_Utilities.CurrentDomain_AssemblyResolve)
    '            AddHandler AppDomain.CurrentDomain.AssemblyResolve, Work
    '            Mod_Utilities.ToolWindowControl_Only.SetContextType(context)

    '            'RemoveHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf Mod_Utilities.CurrentDomain_AssemblyResolve)
    '            RemoveHandler AppDomain.CurrentDomain.AssemblyResolve, Work

    '            Mod_Utilities.LastStackFunction = currentFunction
    '            Mod_Utilities.Log("Done.")
    '        End If
    '    End If
    'End Sub


End Class